<template>
  <el-card style="height: 80px;">
    <el-form :inline="true" class="form">
      <el-form-item label="职位：">
        <el-input placeholder="请输入职位" v-model="keyWord"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary" :disabled="!keyWord">搜索</el-button>
        <el-button @click="reset" type="primary">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0;">
    <el-button @click="addRole" icon="Plus" type="primary">添加职位</el-button>
    <el-table style="margin: 10px  0;" border :data="allRole">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="roleName" show-overflow-tooltip label="职位名称" align="center"></el-table-column>
      <el-table-column prop="createTime" show-overflow-tooltip label="创建时间" align="center"></el-table-column>
      <el-table-column prop="updateTime" show-overflow-tooltip label="更新时间" align="center"></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button @click="setPermisstion(row)" icon="User" type="primary" size="small">分配权限</el-button>
          <el-button @click="updateRole(row)" icon="Edit" type="primary" size="small">编辑</el-button>
          <el-popconfirm @confirm="deleteRole(row.id)" :title="`你确定要删除${row.roleName}?`" width="260px">
            <template #reference>
              <el-button icon="Delete" type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
      :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
      @current-change="getHasRole(pageNo)" @size-change="seizeChange" />
  </el-card>
  <el-dialog v-model="dialogVisit" :title="roleParams.id ? '更新职位' : '添加职位'">
    <el-form ref="form" :model="roleParams" :rules="rules">
      <el-form-item label="职位名称" prop="roleName">
        <el-input v-model="roleParams.roleName" placeholder="职位名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="dialogVisit = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 分配用户菜单权限按钮权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮权限</h4>
    </template>
    <template #default>
      <el-tree ref="tree" style="max-width: 600px" :data="menuArr" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="selectArr" :props="defaultProps" />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqSetPermisstion, reqRemoveRole } from '@/api/acl/role';
import type { RoleResponseData, Records, RoleData, MenuResponseData, MenuList } from '@/api/acl/role/type';
import useLayoutSettingStore from '@/store/modules/setting';
import { ElMessage } from 'element-plus';

// 获取模板setting仓库
let settingStore = useLayoutSettingStore()
// 默认页码
let pageNo = ref<number>(1)
// 一页展示几条数据
let pageSize = ref<number>(10)
// 用户的总个数
let total = ref<number>(0)
// 搜索关键字
let keyWord = ref<string>('')
// 存储全部职位
let allRole = ref<Records>([])
// 控制对话框显示隐藏
let dialogVisit = ref<boolean>(false)
// 收集新增职位数据
let roleParams = reactive<RoleData>({
  roleName: ""
})
// 获取form组件实例
let form = ref<any>()
// 控制抽屉显示隐藏
let drawer = ref<boolean>(false)
// 定义数组存储用户权限数据
let menuArr = ref<MenuList>([])
// 存储勾选节点的ID(四级)
let selectArr = ref<number[]>([])
// 获取tree组件实例
let tree = ref<any>()

onMounted(() => {
  getHasRole()
})

// 获取职位列表
const getHasRole = async (pager = 1) => {
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyWord.value)
  if (result.code == 200) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}

// 下拉菜单
const seizeChange = () => {
  getHasRole()
}

// 搜索按钮
const search = () => {
  getHasRole()
  keyWord.value = ''
}

// 重置按钮
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}

// 添加职位
const addRole = () => {
  dialogVisit.value = true
  // 清空数据
  Object.assign(roleParams, {
    id: '',
    roleName: ''
  })
  // 清空校验
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}

// 更新职位
const updateRole = (row: RoleData) => {
  dialogVisit.value = true
  Object.assign(roleParams, row)
  // 清空校验
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}

// 校验职位名字
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  // 用户名字长度至少五位
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('用户名字至少两位'))
  }
}
// 职位校验规则
const rules = {
  roleName: [
    { required: true, trigger: 'blur', validator: validatorRoleName }
  ]
}

// 确定按钮
const save = async () => {
  // 表单校验结果通过发请求
  await form.value.validate()

  // 添加\修改职位
  let result: any = await reqAddOrUpdateRole(roleParams as RoleData)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: roleParams.id ? '更新成功' : '添加成功'
    })
    dialogVisit.value = false
    getHasRole(roleParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: roleParams.id ? '更新失败' : '添加失败'
    })
  }
}

// 分配权限按钮
const setPermisstion = async (row: RoleData) => {
  drawer.value = true
  Object.assign(roleParams, row)
  let result: MenuResponseData = await reqAllMenuList(roleParams.id)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}

// 树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}

const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  });
  return initArr
}

// 抽屉确定按钮
const confirmClick = async () => {
  const roleId = roleParams.id
  // 选中的ID
  let arr = tree.value.getCheckedKeys()
  // 半选的ID
  let arr1 = tree.value.getHalfCheckedKeys()
  let permisstionId = arr.concat(arr1)

  let result = await reqSetPermisstion(roleId, permisstionId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配权限成功'
    })
    drawer.value = false
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: '分配权限失败'
    })
  }
}

// 删除权限
const deleteRole = async (id: number) => {
  let result = await reqRemoveRole(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除权限成功'
    })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除权限失败'
    })
  }
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>